import { _RouteLocationBase } from "vue-router";
import { TabInfo } from "@/bean/vo/TabInfo";
import MetaUtil from '@/utils/MetaUtil';


export default class PageTabUtil {

  private tabNameSet: Set<string> = new Set();

  private tabList: TabInfo[] = [];

  public get tabs() {
    return Array.from(this.tabList);
  }

  public addFixedTabs(routes: _RouteLocationBase[]) {
    for (const route of routes) {
      const tabName = MetaUtil.getTabName(route);
      this.tabList.push({
        tabName,
        route,
        fixed: true
      });
      this.tabNameSet.add(tabName);
    }
  }

  public onRouterChange(route: _RouteLocationBase) {
    const tabName = MetaUtil.getTabName(route);
    if (tabName) {
      if (!this.tabNameSet.has(tabName)) {
        this.tabList.push({
          tabName,
          route,
          fixed: false
        });
        this.tabNameSet.add(tabName);
      }
    }
  }

  public close(tab: TabInfo): TabInfo {
    if (tab.fixed) {
      return;
    }
    const tabName = tab.tabName;
    const removeIndex = this.tabList.findIndex(item => item.tabName === tabName);
    const list = this.tabList = this.tabList.filter(item => item.tabName !== tabName);
    this.tabNameSet.delete(tabName);
    const length = list.length;
    if (length === 0) {
      return null;
    }
    if (removeIndex < length) {
      return list[removeIndex];
    }
    return list[length - 1];
  }

}
